Execute notebooks

This notebook executes all the FRETBursts tutorial notebooks to automate the creation of notebooks for the FRETBursts_notebooks repository.


In [ ]:
import nbconvert
nbconvert.__version__

In [ ]:
import os
from pathlib import Path

import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from IPython.display import display, FileLink


def run_notebook(in_filepath, run_path=None, out_dir=None, out_suffix=''):
    """Runs the notebook `notebook_name` (file name with no extension).

    This function executes notebook with name `notebook_name` (no extension)
    and saves the fully executed notebook in a new file appending "-out"
    to the original file name.

    It also displays links to the original and executed notebooks.
    """
    if not in_filepath.is_file():
        raise IOError('File "%s" not found.' % in_filepath)
    in_filepath = in_filepath.resolve()
    
    if run_path is None:
        run_path = str(in_filepath.parent)
    
    if out_dir is None:
        out_dir = in_filepath.parent
    else:
        out_dir = Path(out_dir).resolve()
       
    out_filepath = Path(out_dir, "%s%s.ipynb" % (in_filepath.stem, out_suffix))
    
    nb = nbformat.read(in_filepath.open(), as_version=4)
    ep = ExecutePreprocessor(timeout = 3600)

    try:
        out = ep.preprocess(nb, {'metadata': {'path': run_path}})
    except Exception:
        msg = 'Error executing the notebook "%s".\n\n' % in_filepath
        msg += 'See notebook "%s" for the traceback.' % out_filepath
        print(msg)
        raise
    finally:
        nbformat.write(nb, out_filepath.open(mode='wt'))

In [ ]:
%pwd

In [ ]:
pathlist = list(Path('../..').glob('*.ipynb'))
pathlist

In [ ]:
for nbpath in pathlist:
    if not nbpath.stem.startswith('_'):
        print(nbpath.stem)
        run_notebook(nbpath, out_dir=Path(nbpath.parent, 'out'))

In [ ]:
cd ../..

In [ ]:
pwd

In [ ]:
!cp out/*.ipynb ../../FRETBursts_notebooks/notebooks

In [ ]: